<template>
  <div class="device-control-panel">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备控制面板</span>
          <el-tag :type="connected ? 'success' : 'info'">
            {{ connected ? '已连接' : '未连接' }}
          </el-tag>
        </div>
      </template>

      <!-- Connection Section -->
      <div class="control-section">
        <h4>连接控制</h4>
        <el-row :gutter="10">
          <el-col :span="16">
            <el-input 
              v-model="deviceId" 
              placeholder="请输入设备ID"
              :disabled="connected"
            />
          </el-col>
          <el-col :span="8">
            <el-button 
              :type="connected ? 'danger' : 'primary'"
              @click="toggleConnection"
              :loading="connecting"
              style="width: 100%"
            >
              {{ connected ? '断开连接' : '连接设备' }}
            </el-button>
          </el-col>
        </el-row>
      </div>

      <template v-if="connected">
        <!-- Navigation Controls -->
        <div class="control-section">
          <h4>导航控制</h4>
          <el-space wrap>
            <el-button @click="sendBack" icon="ArrowLeft">返回</el-button>
            <el-button @click="sendHome" icon="HomeFilled">主页</el-button>
            <el-button @click="sendMenu" icon="Menu">菜单</el-button>
            <el-button @click="sendRecent" icon="Clock">最近任务</el-button>
          </el-space>
        </div>

        <!-- Swipe Controls -->
        <div class="control-section">
          <h4>滑动控制</h4>
          <div class="swipe-pad">
            <el-button @click="swipeUp" icon="Top" circle class="swipe-btn-up" />
            <div class="swipe-middle">
              <el-button @click="swipeLeft" icon="Back" circle class="swipe-btn-left" />
              <el-button @click="tap" type="primary" circle class="swipe-btn-center">点击</el-button>
              <el-button @click="swipeRight" icon="Right" circle class="swipe-btn-right" />
            </div>
            <el-button @click="swipeDown" icon="Bottom" circle class="swipe-btn-down" />
          </div>
        </div>

        <!-- Text Input -->
        <div class="control-section">
          <h4>文本输入</h4>
          <el-row :gutter="10">
            <el-col :span="18">
              <el-input 
                v-model="textInput" 
                placeholder="输入要发送的文本"
                @keyup.enter="sendTextInput"
                clearable
              />
            </el-col>
            <el-col :span="6">
              <el-button @click="sendTextInput" type="primary" style="width: 100%">
                发送
              </el-button>
            </el-col>
          </el-row>
        </div>

        <!-- Quick Actions -->
        <div class="control-section">
          <h4>快捷操作</h4>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-button-group style="width: 100%">
                <el-button @click="volumeDown" icon="Minus">音量-</el-button>
                <el-button @click="mute" icon="MuteNotification">静音</el-button>
                <el-button @click="volumeUp" icon="Plus">音量+</el-button>
              </el-button-group>
            </el-col>
            <el-col :span="12">
              <el-button-group style="width: 100%">
                <el-button @click="rotateScreen" icon="Refresh">旋转</el-button>
                <el-button @click="toggleScreen" :icon="screenOn ? 'View' : 'Hide'">
                  {{ screenOn ? '关屏' : '开屏' }}
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
        </div>

        <!-- System Panels -->
        <div class="control-section">
          <h4>系统面板</h4>
          <el-space wrap>
            <el-button @click="showNotifications" icon="Bell">通知栏</el-button>
            <el-button @click="showSettings" icon="Setting">快捷设置</el-button>
            <el-button @click="hidePanels" icon="Fold">收起面板</el-button>
          </el-space>
        </div>

        <!-- Clipboard -->
        <div class="control-section">
          <h4>剪贴板操作</h4>
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input 
                v-model="clipboardText" 
                placeholder="剪贴板内容"
                type="textarea"
                :rows="2"
              />
            </el-col>
            <el-col :span="8">
              <el-space direction="vertical" style="width: 100%">
                <el-button @click="setClipboard" style="width: 100%">设置剪贴板</el-button>
                <el-button @click="getClipboard" style="width: 100%">获取剪贴板</el-button>
              </el-space>
            </el-col>
          </el-row>
        </div>

        <!-- Advanced Gestures -->
        <div class="control-section">
          <h4>高级手势</h4>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-button @click="doubleTap" style="width: 100%">双击</el-button>
            </el-col>
            <el-col :span="8">
              <el-button @click="longPress" style="width: 100%">长按</el-button>
            </el-col>
            <el-col :span="8">
              <el-button @click="pinchZoom" style="width: 100%">缩放</el-button>
            </el-col>
          </el-row>
        </div>

        <!-- Custom Touch -->
        <div class="control-section">
          <h4>自定义触摸</h4>
          <div class="touch-area" @click="handleTouchArea">
            <div class="touch-hint">点击此区域模拟触摸</div>
            <div v-if="lastTouch" class="touch-marker" :style="touchMarkerStyle"></div>
          </div>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { DeviceControl } from '@/api/device-control';
import { AndroidKeycode } from '@/types/android-events';

const props = defineProps<{
  deviceId?: string;
}>();

const emit = defineEmits<{
  'update:connected': [value: boolean];
}>();

// State
const deviceId = ref(props.deviceId || '');
const connected = ref(false);
const connecting = ref(false);
const textInput = ref('');
const clipboardText = ref('');
const screenOn = ref(true);
const lastTouch = ref<{ x: number; y: number } | null>(null);

let deviceControl: DeviceControl | null = null;

// Computed
const touchMarkerStyle = computed(() => {
  if (!lastTouch.value) return {};
  return {
    left: `${lastTouch.value.x}px`,
    top: `${lastTouch.value.y}px`,
  };
});

// Connection Management
async function toggleConnection() {
  if (connected.value) {
    await disconnect();
  } else {
    await connect();
  }
}

async function connect() {
  if (!deviceId.value) {
    ElMessage.warning('请输入设备ID');
    return;
  }

  connecting.value = true;
  try {
    deviceControl = new DeviceControl(deviceId.value);
    await deviceControl.start();
    
    deviceControl.onReply((reply) => {
      if (reply.type === 'ClipboardChanged' && reply.clipboard) {
        clipboardText.value = reply.clipboard;
        ElMessage.success('剪贴板已更新');
      }
    });
    
    connected.value = true;
    emit('update:connected', true);
    ElMessage.success('设备连接成功');
  } catch (error) {
    ElMessage.error(`连接失败: ${error}`);
  } finally {
    connecting.value = false;
  }
}

async function disconnect() {
  if (deviceControl) {
    await deviceControl.stop();
    deviceControl = null;
  }
  connected.value = false;
  emit('update:connected', false);
  ElMessage.info('设备已断开连接');
}

// Navigation Controls
async function sendBack() {
  await deviceControl?.sendBackButton();
}

async function sendHome() {
  await deviceControl?.sendHomeButton();
}

async function sendMenu() {
  await deviceControl?.sendMenuButton();
}

async function sendRecent() {
  await deviceControl?.sendKeyPress(AndroidKeycode.KEYCODE_APP_SWITCH);
}

// Swipe Controls
async function swipeUp() {
  await deviceControl?.swipeUp(500, 300);
}

async function swipeDown() {
  await deviceControl?.swipeDown(500, 300);
}

async function swipeLeft() {
  await deviceControl?.swipeLeft(500, 300);
}

async function swipeRight() {
  await deviceControl?.swipeRight(500, 300);
}

async function tap() {
  await deviceControl?.tap(540, 960);
}

// Text Input
async function sendTextInput() {
  if (textInput.value) {
    await deviceControl?.sendText(textInput.value);
    textInput.value = '';
    ElMessage.success('文本已发送');
  }
}

// Volume Controls
async function volumeUp() {
  await deviceControl?.volumeUp();
}

async function volumeDown() {
  await deviceControl?.volumeDown();
}

async function mute() {
  await deviceControl?.mute();
}

// Screen Controls
async function rotateScreen() {
  await deviceControl?.rotateDevice();
}

async function toggleScreen() {
  if (screenOn.value) {
    await deviceControl?.turnScreenOff();
  } else {
    await deviceControl?.turnScreenOn();
  }
  screenOn.value = !screenOn.value;
}

// System Panels
async function showNotifications() {
  await deviceControl?.expandNotificationPanel();
}

async function showSettings() {
  await deviceControl?.expandSettingsPanel();
}

async function hidePanels() {
  await deviceControl?.collapsePanels();
}

// Clipboard
async function setClipboard() {
  if (clipboardText.value) {
    await deviceControl?.setClipboard(clipboardText.value);
    ElMessage.success('剪贴板已设置');
  }
}

async function getClipboard() {
  await deviceControl?.getClipboard();
}

// Advanced Gestures
async function doubleTap() {
  await deviceControl?.tap(540, 960);
  setTimeout(async () => {
    await deviceControl?.tap(540, 960);
  }, 100);
}

async function longPress() {
  await deviceControl?.longPress(540, 960, 1000);
}

async function pinchZoom() {
  await deviceControl?.pinch(540, 960, 200, 400, 500);
}

// Custom Touch Area
async function handleTouchArea(event: MouseEvent) {
  const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  
  // Scale to device coordinates (assuming 1080x1920)
  const deviceX = Math.round((x / rect.width) * 1080);
  const deviceY = Math.round((y / rect.height) * 1920);
  
  lastTouch.value = { x, y };
  await deviceControl?.tap(deviceX, deviceY);
  
  setTimeout(() => {
    lastTouch.value = null;
  }, 500);
}

// Cleanup
onUnmounted(() => {
  disconnect();
});
</script>

<style scoped>
.device-control-panel {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.control-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.control-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.control-section h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.swipe-pad {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.swipe-middle {
  display: flex;
  gap: 10px;
  align-items: center;
}

.swipe-btn-center {
  width: 60px;
  height: 60px;
}

.touch-area {
  position: relative;
  width: 100%;
  height: 300px;
  background: linear-gradient(145deg, #f0f2f5, #fafafa);
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  cursor: crosshair;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.touch-hint {
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  user-select: none;
}

.touch-marker {
  position: absolute;
  width: 20px;
  height: 20px;
  background: rgba(64, 158, 255, 0.6);
  border: 2px solid #409eff;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  pointer-events: none;
  animation: ripple 0.5s ease-out;
}

@keyframes ripple {
  0% {
    width: 20px;
    height: 20px;
    opacity: 1;
  }
  100% {
    width: 40px;
    height: 40px;
    opacity: 0;
  }
}

.el-button-group {
  display: flex;
  width: 100%;
}

.el-button-group .el-button {
  flex: 1;
}
</style>